import base64
import cv2
import socket
import threading
import time

import numpy as np


def recvall(sock, count):
    buf = b''
    while count:
        try:
            newbuf = sock.recv(count)
        except:
            return
        if not newbuf:
            return None
        buf += newbuf
        count -= len(newbuf)
    return buf


def handle_client(client_socket, addr):
    while True:
        try:
            length = recvall(client_socket, 16)  # 接收数据长度
            if not length:
                break
            try:
                string_data = recvall(client_socket, int(length.decode('utf-8').strip()))  # 收到的文本内容
                if not string_data:
                    break
            except:
                break
            decoded_data = base64.b64decode(string_data)
            np_data = np.frombuffer(decoded_data, dtype=np.uint8)
            frame = cv2.imdecode(np_data, cv2.IMREAD_COLOR)
            print("收到一个图片")
            cv2.imshow("img", frame)
            cv2.waitKey(1)

        except ConnectionResetError:
            print(f"客户端{addr}连接中断")
            break


port = 5050
host = socket.gethostname()
ip = socket.gethostbyname(host)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen(5)
print("等待连接...")
client_socket, addr = server.accept()
print("连接成功")
# 创建一个新线程来处理客户端连接
client_handler = threading.Thread(target=handle_client, args=(client_socket, addr))
client_handler.start()
stop = False
while True:
    if stop:
        break
    time.sleep(1)
